package br.biofoco.p2p.storage;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class HSQLStorageServer {
	
	private Connection connection;	
	
	public void start() throws IOException, SQLException {
		getConnection();
		createSchema();
		populate();
		queryAll();
	}

	private void queryAll() throws SQLException {
		ResultSet rs = executeSQL(SchemaLoader.QUERY_TABLE);
		
		while (rs.next()) {
			System.out.println(rs.getString("COMMAND"));
		}
		
	}

	private void populate() throws SQLException {
		for (int i = 0; i < 100; i++)
			executeSQL(SchemaLoader.INSERT_TABLE);
	}


	private void getConnection() throws SQLException {
		  try {
		      Class.forName("org.hsqldb.jdbcDriver" );
			  connection = DriverManager.getConnection("jdbc:hsqldb:mem:mymemdb", "SA", "");		      
		  } catch (Exception e) {
		      System.err.println("ERROR: failed to load HSQLDB JDBC driver.");
		      e.printStackTrace();
		      return;
		  }		
	}
	
	private void createSchema() throws SQLException {
		executeSQL(SchemaLoader.CREATE_TABLE);
	}

	private ResultSet executeSQL(String sql) throws SQLException {
		Statement stmt = connection.createStatement();
		stmt.execute(sql);
		return stmt.getResultSet();		
	}
	
	public static void main(String[] args) throws IOException, SQLException {
		new HSQLStorageServer().start();
	}

}
